<template>
  <div class="m-wangEditor">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      mode="default"
    />
    <Editor
      class="editor-content'"
      style="height: 300px; overflow-y: hidden"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      mode="default"
      @onCreated="handleCreated"
    />
  </div>
</template>
<script lang="ts" setup>
  // 引入 wangEditor
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
  import { SlateElement } from '@wangeditor/editor'
  import '@wangeditor/editor/dist/css/style.css' // 引入 css
  import { onBeforeUnmount, onMounted, shallowRef, ref, onBeforeUpdate } from 'vue'
  import { deleteFile } from '../../api/upload'

  // 编辑器实例，必须用 shallowRef
  const editorRef = shallowRef()

  const allImages = ref([]) // 上传的所有图片
  const deleteImages = ref([]) // 删除的所有图片地址

  const allUrls = ref([])
  const ediorUrls = ref([])

  // content——文本内容  type——地址类型
  const props = defineProps({
    all_data: Object,
  })

  const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
  }

  const valueHtml = ref('')

  // 组件销毁时，也及时销毁编辑器
  onBeforeUnmount(() => {
    // 调用销毁 API 对当前编辑器实例进行销毁
    const editor = editorRef.value
    if (editor == null) {
      return
    }
    editor.destroy()
  })

  // 内容回显
  onBeforeUpdate(() => {
    if (props.all_data.content) {
      valueHtml.value = props.all_data.content
    }
  })

  // 获取富文本内容
  const getValue = () => {
    return editorRef.value.getHtml()
  }

  // 获取富文本内容
  const clearValue = () => {
    valueHtml.value = ''
    editorRef.value.setHtml('')
  }

  // 菜单栏配置
  const toolbarConfig = {}

  // 编辑器配置
  const editorConfig = {
    MENU_CONF: {},
    placeholder: '请输入内容...',
  }

  //上传图片的配置
  editorConfig.MENU_CONF['uploadImage'] = {
    // 请求头
    headers: {
      [useUserStore().row.tokenName]: localStorage.getItem('token'),
    },
    fieldName: 'files', // 参数名称
    server:
      props.all_data.type == 'goods'
        ? 'http://localhost:8080/dev-api/file/annex/goods'
        : 'http://localhost:8080/dev-api/file/annex/knowledge', // 请求地址

    // 自定义插入图片
    customInsert(res, insertFn) {
      insertFn(res.data.rows[0])
    },
  }

  type ImageElement = SlateElement & {
    src: string
    alt: string
    url: string
    href: string
  }

  // 插入图片
  editorConfig.MENU_CONF['insertImage'] = {
    onInsertedImage(imageNode: ImageElement | null) {
      if (imageNode == null) return
      const { src, alt, url, href } = imageNode
      allImages.value.push(imageNode)
    },
  }

  // 获取图片地址
  const getUrls = () => {
    allUrls.value = []
    ediorUrls.value = []
    allImages.value.forEach((item) => {
      allUrls.value.push(item.src)
    })
    editorRef.value.getElemsByType('image').forEach((item) => {
      ediorUrls.value.push(item.src)
    })
  }

  // 获取删除的图片
  const getDeleteImages = () => {
    getUrls()
    deleteImages.value = []
    allUrls.value.forEach((item) => {
      if (!ediorUrls.value.includes(item)) {
        deleteImages.value.push(item)
      }
    })
    deleImages()
  }

  // 删除上传的图片
  const deleImages = () => {
    if (deleteImages.value.length != 0) {
      deleteFile(deleteImages.value).then()
    }
  }

  // 上传视频的配置
  editorConfig.MENU_CONF['uploadVideo'] = {
    // 请求头
    headers: {
      [useUserStore().row.tokenName]: localStorage.getItem('token'),
    },
    fieldName: 'files', // 参数名称
    server: 'http://localhost:8080/dev-api/file/annex/goods', // 请求地址

    // 自定义插入
    customInsert(res, insertFn) {
      insertFn(res.data.rows[0])
    },
  }

  defineExpose({ getValue, clearValue, getDeleteImages })
</script>

<style lang="scss" scoped>
  .m-wangEditor {
    z-index: 1000;
    width: 100%;
    box-sizing: border-box;
    border: 1px solid #cccccc;
    .editor-toolbar {
      border-bottom: 1px solid #cccccc;
    }
    .editor-content {
      overflow-y: hidden;
    }
  }
</style>
